package problem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author RunningShrimp
 * @date 2021/5/19  15:02
 * @see <a href="https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/">350. 两个数组的交集 II</a>
 */
public class TwoArrayIntersection2 {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> integerIntegerMap = new HashMap<>();
        for (int i : nums1) {
            if (integerIntegerMap.containsKey(i)) {
                integerIntegerMap.put(i, integerIntegerMap.get(i) + 1);
            } else {
                integerIntegerMap.put(i, 1);
            }
        }
        List<Integer> list = new ArrayList<>();
        for (int i : nums2) {
            if (integerIntegerMap.containsKey(i)) {
                list.add(i);
                int time=integerIntegerMap.get(i) - 1;
                if(time == 0){
                    integerIntegerMap.remove(i);
                }
                integerIntegerMap.put(i, time);
            }
        }
        int[] array = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }
}
